package com.cmc6.common.config;

import cn.hutool.core.util.ArrayUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.ssl.SSLContextBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import javax.annotation.Resource;

@Configuration
@EnableElasticsearchRepositories(basePackages = "com.cmc6")
@Slf4j
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {

    @Resource
    ElasticsearchRestClientProperties elasticsearchRestClientProperties;

    @SneakyThrows
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            .connectedTo(ArrayUtil.toArray(elasticsearchRestClientProperties.getUris(), String.class))
            // 信任所有 SSL证书
            .usingSsl(new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build(),
                NoopHostnameVerifier.INSTANCE).withBasicAuth(elasticsearchRestClientProperties.getUsername(),
                elasticsearchRestClientProperties.getPassword()).build();

        log.info("Elasticsearch 启动");
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }

}
